<template>
  <div class="api-test-container">
    <h1>商品库存API测试页面</h1>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>用户登录</h2>
        </div>
      </template>
      <div class="api-section">
        <h3>用户登录</h3>
        <el-form :model="loginForm" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ loginResult }}</pre>
        </div>
      </div>
    </el-card>

    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>库存API测试</h2>
        </div>
      </template>
      
      <!-- 获取库存列表 -->
      <div class="api-section">
        <h3>1. 获取库存列表</h3>
        <el-form :model="getInventoryForm" label-width="120px">
          <el-form-item label="仓库ID">
            <el-input v-model="getInventoryForm.warehouse_id" placeholder="请输入仓库ID"></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="getInventoryForm.product_name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="getInventoryForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="正常" value="normal"></el-option>
              <el-option label="预警" value="warning"></el-option>
              <el-option label="超量" value="overflow"></el-option>
              <el-option label="过期" value="expired"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetInventory">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getInventoryResult }}</pre>
        </div>
      </div>
      
      <!-- 获取低库存商品 -->
      <div class="api-section">
        <h3>2. 获取低库存商品</h3>
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="handleGetLowStock">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getLowStockResult }}</pre>
        </div>
      </div>
      
      <!-- 调整库存 -->
      <div class="api-section">
        <h3>3. 调整库存</h3>
        <el-form :model="adjustInventoryForm" label-width="120px">
          <el-form-item label="库存ID">
            <el-input v-model="adjustInventoryForm.inventory_id" placeholder="请输入库存ID"></el-input>
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="adjustInventoryForm.operation_type" placeholder="请选择操作类型">
              <el-option label="入库" value="in"></el-option>
              <el-option label="出库" value="out"></el-option>
              <el-option label="调整" value="adjust"></el-option>
              <el-option label="转移" value="transfer"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number v-model="adjustInventoryForm.quantity" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="源仓库ID" v-if="adjustInventoryForm.operation_type === 'transfer'">
            <el-input v-model="adjustInventoryForm.source_warehouse_id" placeholder="请输入源仓库ID"></el-input>
          </el-form-item>
          <el-form-item label="目标仓库ID" v-if="adjustInventoryForm.operation_type === 'transfer'">
            <el-input v-model="adjustInventoryForm.target_warehouse_id" placeholder="请输入目标仓库ID"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="adjustInventoryForm.note" type="textarea" placeholder="请输入备注"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdjustInventory">调整</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ adjustInventoryResult }}</pre>
        </div>
      </div>
      
      <!-- 获取库存记录 -->
      <div class="api-section">
        <h3>4. 获取库存记录</h3>
        <el-form :model="getRecordsForm" label-width="120px">
          <el-form-item label="库存ID">
            <el-input v-model="getRecordsForm.inventory_id" placeholder="请输入库存ID"></el-input>
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="getRecordsForm.operation_type" placeholder="请选择操作类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="入库" value="in"></el-option>
              <el-option label="出库" value="out"></el-option>
              <el-option label="调整" value="adjust"></el-option>
              <el-option label="转移" value="transfer"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="getRecordsForm.start_date" type="date" placeholder="请选择开始日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="getRecordsForm.end_date" type="date" placeholder="请选择结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGetRecords">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getRecordsResult }}</pre>
        </div>
      </div>
      
      <!-- 获取仓库列表 -->
      <div class="api-section">
        <h3>5. 获取仓库列表</h3>
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="handleGetWarehouses">获取</el-button>
          </el-form-item>
        </el-form>
        <div class="api-result">
          <h4>结果：</h4>
          <pre>{{ getWarehousesResult }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 用户登录
const loginForm = reactive({
  username: '',
  password: ''
});
const loginResult = ref('');

const handleLogin = async () => {
  try {
    const response = await axios.post('/api/users/login/', loginForm);
    loginResult.value = JSON.stringify(response.data, null, 2);
    if (response.data.access) {
      localStorage.setItem('token', response.data.access);
      ElMessage.success('登录成功');
    } else {
      ElMessage.error('登录失败: 未获取到token');
    }
  } catch (error) {
    loginResult.value = JSON.stringify(error.response?.data || error.message, null, 2);
    ElMessage.error('登录失败');
  }
};

// 获取token
const getToken = () => {
  return localStorage.getItem('token')
}

// 获取库存列表
const getInventoryForm = reactive({
  warehouse_id: '',
  product_name: '',
  status: ''
});
const getInventoryResult = ref('');

const handleGetInventory = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.warning('请先登录');
      return;
    }
    
    const params = {};
    if (getInventoryForm.warehouse_id) params.warehouse_id = getInventoryForm.warehouse_id;
    if (getInventoryForm.product_name) params.product_name = getInventoryForm.product_name;
    if (getInventoryForm.status) params.status = getInventoryForm.status;
    
    console.log('发送请求到:', '/api/inventory/');
    console.log('请求参数:', params);
    console.log('认证Token:', token.substring(0, 10) + '...');
    
    const response = await axios.get(
      '/api/inventory/',
      {
        params,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      }
    );
    
    console.log('API响应:', response);
    
    if (typeof response.data === 'string') {
      getInventoryResult.value = '返回了HTML页面而不是JSON数据，可能是API端点错误或认证问题';
      ElMessage.error('API返回了非JSON数据');
    } else {
      getInventoryResult.value = JSON.stringify(response.data, null, 2);
    }
  } catch (error) {
    console.error('获取库存失败:', error);
    if (error.response) {
      getInventoryResult.value = JSON.stringify(error.response.data, null, 2);
      ElMessage.error(`获取库存失败: ${error.response.status} ${error.response.statusText}`);
    } else {
      getInventoryResult.value = JSON.stringify(error.message, null, 2);
      ElMessage.error('获取库存失败: ' + error.message);
    }
  }
};

// 获取低库存商品
const getLowStockResult = ref('');

const handleGetLowStock = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.warning('请先登录');
      return;
    }
    
    console.log('发送请求到:', '/api/inventory/low_stock/');
    
    const response = await axios.get(
      '/api/inventory/low_stock/',
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      }
    );
    
    console.log('API响应:', response);
    
    if (typeof response.data === 'string') {
      getLowStockResult.value = '返回了HTML页面而不是JSON数据，可能是API端点错误或认证问题';
      ElMessage.error('API返回了非JSON数据');
    } else {
      getLowStockResult.value = JSON.stringify(response.data, null, 2);
    }
  } catch (error) {
    console.error('获取低库存商品失败:', error);
    if (error.response) {
      getLowStockResult.value = JSON.stringify(error.response.data, null, 2);
      ElMessage.error(`获取低库存商品失败: ${error.response.status} ${error.response.statusText}`);
    } else {
      getLowStockResult.value = JSON.stringify(error.message, null, 2);
      ElMessage.error('获取低库存商品失败: ' + error.message);
    }
  }
};

// 调整库存
const adjustInventoryForm = reactive({
  inventory_id: '',
  operation_type: 'in',
  quantity: 1,
  source_warehouse_id: '',
  target_warehouse_id: '',
  note: ''
});
const adjustInventoryResult = ref('');

const handleAdjustInventory = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.warning('请先登录');
      return;
    }
    
    if (!adjustInventoryForm.inventory_id) {
      ElMessage.warning('请输入库存ID');
      return;
    }
    
    if (!adjustInventoryForm.operation_type) {
      ElMessage.warning('请选择操作类型');
      return;
    }
    
    if (adjustInventoryForm.operation_type === 'transfer') {
      if (!adjustInventoryForm.source_warehouse_id) {
        ElMessage.warning('请输入源仓库ID');
        return;
      }
      
      if (!adjustInventoryForm.target_warehouse_id) {
        ElMessage.warning('请输入目标仓库ID');
        return;
      }
    }
    
    const data = {
      inventory_id: adjustInventoryForm.inventory_id,
      operation_type: adjustInventoryForm.operation_type,
      quantity: adjustInventoryForm.quantity,
      note: adjustInventoryForm.note || ''
    };
    
    if (adjustInventoryForm.operation_type === 'transfer') {
      data.source_warehouse_id = adjustInventoryForm.source_warehouse_id;
      data.target_warehouse_id = adjustInventoryForm.target_warehouse_id;
    }
    
    console.log('发送请求到:', '/api/inventory/adjust/');
    console.log('请求数据:', data);
    
    const response = await axios.post(
      '/api/inventory/adjust/',
      data,
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }
    );
    
    console.log('API响应:', response);
    
    if (typeof response.data === 'string') {
      adjustInventoryResult.value = '返回了HTML页面而不是JSON数据，可能是API端点错误或认证问题';
      ElMessage.error('API返回了非JSON数据');
    } else {
      adjustInventoryResult.value = JSON.stringify(response.data, null, 2);
      ElMessage.success('调整库存成功');
    }
  } catch (error) {
    console.error('调整库存失败:', error);
    if (error.response) {
      adjustInventoryResult.value = JSON.stringify(error.response.data, null, 2);
      ElMessage.error(`调整库存失败: ${error.response.status} ${error.response.statusText}`);
    } else {
      adjustInventoryResult.value = JSON.stringify(error.message, null, 2);
      ElMessage.error('调整库存失败: ' + error.message);
    }
  }
};

// 获取库存记录
const getRecordsForm = reactive({
  inventory_id: '',
  operation_type: '',
  start_date: '',
  end_date: ''
});
const getRecordsResult = ref('');

const handleGetRecords = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.warning('请先登录');
      return;
    }
    
    const params = {};
    if (getRecordsForm.inventory_id) params.inventory_id = getRecordsForm.inventory_id;
    if (getRecordsForm.operation_type) params.operation_type = getRecordsForm.operation_type;
    if (getRecordsForm.start_date) params.start_date = getRecordsForm.start_date;
    if (getRecordsForm.end_date) params.end_date = getRecordsForm.end_date;
    
    console.log('发送请求到:', '/api/inventory/records/');
    console.log('请求参数:', params);
    
    const response = await axios.get(
      '/api/inventory/records/',
      {
        params,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      }
    );
    
    console.log('API响应:', response);
    
    if (typeof response.data === 'string') {
      getRecordsResult.value = '返回了HTML页面而不是JSON数据，可能是API端点错误或认证问题';
      ElMessage.error('API返回了非JSON数据');
    } else {
      getRecordsResult.value = JSON.stringify(response.data, null, 2);
    }
  } catch (error) {
    console.error('获取库存记录失败:', error);
    if (error.response) {
      getRecordsResult.value = JSON.stringify(error.response.data, null, 2);
      ElMessage.error(`获取库存记录失败: ${error.response.status} ${error.response.statusText}`);
    } else {
      getRecordsResult.value = JSON.stringify(error.message, null, 2);
      ElMessage.error('获取库存记录失败: ' + error.message);
    }
  }
};

// 获取仓库列表
const getWarehousesResult = ref('');

const handleGetWarehouses = async () => {
  try {
    const token = getToken();
    if (!token) {
      ElMessage.warning('请先登录');
      return;
    }
    
    console.log('发送请求到:', '/api/warehouses/');
    
    const response = await axios.get(
      '/api/warehouses/',
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      }
    );
    
    console.log('API响应:', response);
    
    if (typeof response.data === 'string') {
      getWarehousesResult.value = '返回了HTML页面而不是JSON数据，可能是API端点错误或认证问题';
      ElMessage.error('API返回了非JSON数据');
    } else {
      getWarehousesResult.value = JSON.stringify(response.data, null, 2);
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error);
    if (error.response) {
      getWarehousesResult.value = JSON.stringify(error.response.data, null, 2);
      ElMessage.error(`获取仓库列表失败: ${error.response.status} ${error.response.statusText}`);
    } else {
      getWarehousesResult.value = JSON.stringify(error.message, null, 2);
      ElMessage.error('获取仓库列表失败: ' + error.message);
    }
  }
};
</script>

<style scoped>
.api-test-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.api-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.api-section:last-child {
  border-bottom: none;
}

.api-result {
  margin-top: 15px;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}
</style>